const request = require('../../utils/request.js'); // 引入封装好的 request 方法

Page({
  data: {
    nickname: '',
    avatarUrl: ''
  },

  onLogin() {
    const { nickname, avatarUrl } = this.data;

    if (!nickname || !avatarUrl) {
      wx.showToast({
        title: '请填写昵称并选择头像',
        icon: 'none'
      });
      return;
    }

    wx.login({
      success: (res) => {
        if (res.code) {
          // 登录请求，不需要 token
          request.request({
            url: '/wx/login',
            method: 'POST',
            data: {
              code: res.code,
              nickname: nickname,
              avatarUrl: avatarUrl
            },
            requireAuth: false // 不需要 token 验证
          }).then(response => {
            const token = response.data.data.token;
            const expiresIn = response.data.data.expiresIn;
            if (token) {
              //存放token并设置过期时间
              request.onLoginSuccess(token,expiresIn);
              wx.redirectTo({
                url: '/pages/chat/chat'
              });
            } else {
              wx.showToast({
                title: '登录失败，请重试',
                icon: 'none'
              });
            }
          }).catch(error => {
            wx.showToast({
              title: '请求失败',
              icon: 'none'
            });
            console.error('请求错误：', error);
          });
        }
      }
    });
  },

  onChooseAvatar(e) {
    this.setData({
      avatarUrl: e.detail.avatarUrl
    });
  },

  onInputChange(e) {
    this.setData({
      nickname: e.detail.value
    });
  }
});